package 多线程;

/*
    线程通信的应用:
        生产者(Producer)将产品交给店员(Clerk),而消费者(Customer)从店员处取走产品,
        店员一次只能持有固定数量的产品(比如:20),如果生产者试图生产更多的产品,店员会叫生产者停一下,
        如果店中有空位放产品了再通知生产者继续生产,如果店中没有产品了,店员会告诉消费者等一下,
        如果店中有产品了再通知消费者来取走产品

    这里可能出现两个问题:
        生产者比消费者快时,消费者会漏掉一些数据没有取到
        消费者比生产者快时,消费者会取相同的数据
 */
public class ThreadTest14 {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();

        Producer producer = new Producer(clerk);
        producer.setName("生产者");

        Custom custom = new Custom(clerk);
        custom.setName("消费者");

        producer.start();
        custom.start();
    }
}

//店员
class Clerk{

    private Integer productCount = 0;

    //生产产品
    public synchronized void produceProduct() {
        if(productCount < 20){
            productCount++;
            System.out.println(Thread.currentThread().getName() + "开始生产第" + productCount + "个商品...");
            this.notify();
        }else {
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //消费产品
    public synchronized void consumeProduct() {
        if(productCount > 0){
            System.out.println(Thread.currentThread().getName() + "开始消费第" + productCount + "个商品...");
            productCount--;
            notify();
        } else {
            //等待
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//生产者
class Producer extends Thread{

    private Clerk clerk;

    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始生产商品...");

        while(true){

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            this.clerk.produceProduct();
        }

    }
}

//消费者
class Custom extends Thread{

    private Clerk clerk;

    public Custom(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "开始消费商品...");
        while (true){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            this.clerk.consumeProduct();
        }
    }
}
